package com.besall.allbase.view.activity.tools.AudioListActivity;

/**
 * @author ericshen
 * @time $ $
 */

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import com.besall.allbase.common.utils.ActivityUtils;
import com.besall.allbase.common.utils.LogUtils;
import com.besall.allbase.common.utils.SlideLayout;
import com.besall.allbase.view.activity.tools.FileActivity.FileEntity;
import com.besall.allbase.view.base.BaseActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import bb.lanxing.R;

//import static bb.lanxing.R.drawable.chips_tools_icon_sound_play;
//import static bb.lanxing.R.drawable.chips_tools_icon_stop;
//import static com.besall.allbase.common.utils.ActivityUtils.logI;
//import static com.besall.allbase.common.utils.ActivityUtils.showToast;
//import static com.besall.allbase.common.utils.FileUtils.getFolderPath;

public class AudioListActivity extends BaseActivity<IAudioListActivity, AudioListPresenter>
        implements IAudioListActivity, AdapterView.OnItemClickListener {
    private static final String TAG = "AudioListActivity";
    private static AudioListActivity instance;
    public String cur_title = "FILES";
    public boolean audioplay = false;
    public int hp = -1;
    public ImageView imageViewIV;
    public SlideLayout slideLayout = null;
    String sdRootPath;
    private ListView mListView;
    private MyFileAdapter mAdapter;
    private AudioListActivity mContext;
    private File currentFile;
    private ArrayList<FileEntity> mList;
    private Set<SlideLayout> sets = new HashSet();
    private Handler mHandler;

    @Override
    protected AudioListPresenter createPresenter() {

        return new AudioListPresenter();
    }

    @Override
    protected void initBeforeSetContent() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.file_list;
    }

    @Override
    protected void bindView() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                case 1:
                    if (mAdapter == null) {
                        Log.i(TAG, "handleMessage: -111");
                        mAdapter = new MyFileAdapter(mContext, mList);
                        mListView.setAdapter(mAdapter);
                    } else {
                        Log.i(TAG, "handleMessage: -2222");
                        ;
                        mAdapter.notifyDataSetChanged();
                    }

                    break;
                case 2:

                    break;

                default:
                    break;
                }
            }
        };
        mListView = (ListView) findViewById(R.id.filename);
        mContext = this;
        mList = new ArrayList<>();
        // sdRootPath = getFolderPath()+"BES/"+"LogData/"+"AudioDump/";
        currentFile = getExternalFilesDir("AudioDump");
        Log.i(TAG, "bindView: " + currentFile);
        // System.out.println(sdRootPath);
        initView();
        getData();
    }

    public void initView() {
        inittoolbar(cur_title);
        audioplay = false;
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
    }

    @Override
    protected void setInstance() {
        instance = this;
    }

    @Override
    protected void removeInstance() {
        instance = null;
    }

    private void getData() {
        new Thread() {
            @Override
            public void run() {
                super.run();

                findAllFiles();
            }
        }.start();

    }

    /**
     * 查找path地址下所有文件
     *
    //     * @param path
     */
    public void findAllFiles() {
        mList.clear();

        // if (path == null || path.equals("")) {
        // return;
        // }
        File fatherFile = getExternalFilesDir("AudioDump");
        File[] files = fatherFile.listFiles();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                FileEntity entity = new FileEntity();
                boolean isDirectory = files[i].isDirectory();
                if (isDirectory == true) {
                    entity.setFileType(FileEntity.Type.FLODER);
                    // entity.setFileName(files[i].getPath());
                } else {
                    entity.setFileType(FileEntity.Type.FILE);
                }
                entity.setFileName(files[i].getName().toString());
                entity.setFilePath(files[i].getAbsolutePath());
                entity.setFileSize(files[i].length() + "");
                entity.setPlaystatus(false);
                mList.add(entity);
            }
        }
        mHandler.sendEmptyMessage(1);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {
            finish();
        }

        /*
         * switch (item.getItemId()) { case android.R.id.home: this.finish(); break; }
         */
        return super.onOptionsItemSelected(item);
    }

    protected void LOG(String msg) {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            LogUtils.e_write(TAG, msg + "");
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    public void audiodone() {

        Log.i(TAG, "audiodone: ++++++");
        imageViewIV.setImageResource(R.drawable.ic_sound_play);
        audioplay = false;

    }

    class MyFileAdapter extends BaseAdapter {
        private Context mContext;
        private ArrayList<FileEntity> mAList;
        private LayoutInflater mInflater;

        public MyFileAdapter(AudioListActivity mContext, ArrayList<FileEntity> mList) {
            super();
            this.mContext = mContext;
            this.mAList = mList;
            mInflater = LayoutInflater.from(mContext);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mAList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return mAList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemViewType(int position) {
            if (mAList.get(position).getFileType() == FileEntity.Type.FLODER) {
                return 0;
            } else {
                return 1;
            }
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @SuppressLint("ResourceAsColor")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // System.out.println("position-->"+position+" ---convertView--"+convertView);
            ViewHolder holder = null;
            // int type = getItemViewType(position);
            FileEntity entity = mAList.get(position);

            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.item_audio_list, parent, false);
                holder.Content = (View) convertView.findViewById(R.id.content);
                holder.iv = (ImageView) convertView.findViewById(R.id.item_imageview);
                holder.tv = (TextView) convertView.findViewById(R.id.file_name);
                holder.file_size = (TextView) convertView.findViewById(R.id.file_size);
                holder.dv = (TextView) convertView.findViewById(R.id.delete_button);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            Log.i(TAG, "getView: finalHolder");
            ;
            ViewHolder finalHolder = holder;

            holder.iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i(TAG, "onItemClick: +1");
                    final FileEntity entity = mList.get(position);
                    Log.i(TAG, "onClick: +++++" + hp + "  " + position);
                    Log.i(TAG, "getView: tag1---" + v);
                    runOnUiThread(new Runnable() {
                        @SuppressLint("ResourceAsColor")
                        @Override
                        public void run() {
                            Log.i(TAG, "onItemClick: +++file");
                            if (audioplay == false) {
                                hp = position;
                                Log.i(TAG, "run: audioplay" + audioplay);
                                Log.i(TAG, "run: item ++" + getItemId(position));
                                finalHolder.tv.setTextColor(R.color.listtvd);
                                finalHolder.iv.setImageResource(R.drawable.ic_sound_stop);
                                mPresenter.player(AudioListActivity.this, entity.getFilePath(), 0);
                                v.setTag(finalHolder.iv);
                                imageViewIV = (ImageView) v.getTag();
                                Log.i(TAG, "set1: imageViewIV" + imageViewIV);
                                audioplay = true;
                                entity.setPlaystatus(true);
                                Log.i(TAG, "run: hp" + hp);
                            } else {
                                if (hp == position) {
                                    Log.i(TAG, "run: stop");
                                    mPresenter.stopplay(entity.getFileName());
                                    finalHolder.iv.setImageResource(R.drawable.ic_sound_play);
                                    audioplay = false;
                                    entity.setPlaystatus(false);
                                    return;
                                }
                                Log.i(TAG, "run222: audioplay" + audioplay);
                                Log.i(TAG, "get1: imageViewIV" + imageViewIV);
                                final FileEntity lastentity = mList.get(hp);
                                mPresenter.stopplay(lastentity.getFilePath());
                                finalHolder.tv.setTextColor(R.color.listtv);
                                imageViewIV.setImageResource(R.drawable.ic_sound_play);
                                Log.i(TAG, "check1: imageViewIV" + imageViewIV);

                                v.setTag(finalHolder.iv);
                                Log.i(TAG, "run: v" + v);
                                imageViewIV = (ImageView) v.getTag();
                                Log.i(TAG, "set1: imageViewIV" + imageViewIV);
                                imageViewIV.setImageResource(R.drawable.ic_sound_stop);
                                mPresenter.player(AudioListActivity.this, entity.getFilePath(), 0);
                                audioplay = true;
                                entity.setPlaystatus(true);
                                Log.i(TAG, "run: ----" + entity.getPlaystatus());
                                hp = position;
                            }

                            ActivityUtils.showToast(entity.getFilePath());

                        }
                    });
                }
            });

            holder.dv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    SlideLayout slideLayout = (SlideLayout) v.getParent();
                    slideLayout.closeMenu();
                    File file = new File(entity.getFilePath());
                    file.delete();
                    mList.remove(entity);
                    notifyDataSetChanged();
                }
            });

            if (entity.getPlaystatus() == false) {
                holder.iv.setImageResource(R.drawable.ic_sound_play);
            } else {
                holder.iv.setImageResource(R.drawable.ic_sound_stop);
            }
            holder.iv.setScaleX(1.5f);
            holder.iv.setScaleY(1.5f);
            holder.tv.setText(entity.getFileName());

            float size = Float.parseFloat(entity.getFileSize()) / 1024;
            BigDecimal fs = new BigDecimal(size);
            float fsz = fs.setScale(4, BigDecimal.ROUND_HALF_UP).floatValue();
            holder.file_size.setText(fsz + "KB");
            SlideLayout slideLayout = (SlideLayout) convertView;
            slideLayout.setOnStateChangeListener(new MyOnStateChangeListener());

            return convertView;
        }

    }

    class ViewHolder {
        View Content;
        ImageView iv;
        TextView tv;
        TextView file_size;
        TextView dv;
    }

    class MyOnStateChangeListener implements SlideLayout.OnStateChangeListener {
        /**
         * 滑动后每次手势抬起保证只有一个item是open状态，加入sets集合中
         **/
        @Override
        public void onOpen(SlideLayout layout) {
            slideLayout = layout;
            if (sets.size() > 0) {
                for (SlideLayout s : sets) {
                    s.closeMenu();
                    sets.remove(s);
                    Log.i(TAG, "onOpen: 111");
                    if (audioplay == true) {
                        final FileEntity lastentity = mList.get(hp);
                        mPresenter.stopplay(lastentity.getFileName());
                        imageViewIV.setImageResource(R.drawable.ic_sound_play);
                    }
                }
            }
            sets.add(layout);
            Log.i(TAG, "open: ----------");
            if (audioplay == true) {
                final FileEntity lastentity = mList.get(hp);
                mPresenter.stopplay(lastentity.getFileName());
            }
        }

        @Override
        public void onMove(SlideLayout layout) {
            if (slideLayout != null && slideLayout != layout) {
                Log.i(TAG, "onMove: ----------");
                slideLayout.closeMenu();

            }
        }

        @Override
        public void onClose(SlideLayout layout) {
            if (sets.size() > 0) {
                sets.remove(layout);
            }
            if (slideLayout == layout) {
                slideLayout = null;
            }
        }

    }

}
